<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Http\Model\Goods;
use App\Http\Model\ClothingAttr;
use App\Http\Model\Address;
use App\Http\Model\Orders;
use App\Http\Model\OrdersInfo;
use App\Http\Model\User;
use DB;
use EasyWeChat\Payment\Order;
use EasyWeChat\Foundation\Application;
use Config;

class CartController extends Controller{
    // 购物车页面
    public function cart(){
        $goodsInfo = session("cart");
        return view("home.cart.cart", ["goodsInfo" => $goodsInfo]);
    }
    // ajax立即购买
    public function saveConfirm(Request $request){
        $data = $request->all();
        $goods = new Goods;
        $clothingAttr = new ClothingAttr;
        $goodsInfo = $goods->find($data['goods']);
        $clothingAttrInfo = $clothingAttr->where("clothing_spec_id",$data['spec'])->where("goods_id",$data['goods'])->first();
        if($clothingAttrInfo && $goodsInfo){
            session()->forget('confirm');
            $confirm = array();
            $confirm['goods_id'] = $goodsInfo->id;
            $confirm['goods_name'] = $goodsInfo->name;
            $confirm['goods_spec'] = $goodsInfo->spec;
            $confirm['pic'] = $goodsInfo->pic;
            $confirm['express_price'] = $goodsInfo->express_price;
            $confirm['clothing_attr_id'] = $clothingAttrInfo->id;
            $confirm['pre_price'] = $clothingAttrInfo->pre_price;
            $confirm['price'] = $clothingAttrInfo->price;
            $confirm['num'] = $data['num'];
            $confirm['spec'] = $clothingAttrInfo->clothingSpec->name;
            session(['confirm' => $confirm]);
            session()->save();
            // dd(session()->all());
            echo 1;
        }else{
            echo 0;
        }
    }
    // ajax加入购物车
    public function saveCart(Request $request){
        $data = $request->all();
        $goods = new Goods;
        $clothingAttr = new ClothingAttr;
        $goodsInfo = $goods->find($data['goods']);
        $clothingAttrInfo = $clothingAttr->where("clothing_spec_id",$data['spec'])->where("goods_id",$data['goods'])->first();
        if($clothingAttrInfo && $goodsInfo){
            $confirm = array();
            $confirm['goods_id'] = $goodsInfo->id;
            $confirm['goods_name'] = $goodsInfo->name;
            $confirm['goods_spec'] = $goodsInfo->spec;
            $confirm['pic'] = $goodsInfo->pic;
            $confirm['express_price'] = $goodsInfo->express_price;
            $confirm['clothing_attr_id'] = $clothingAttrInfo->id;
            $confirm['pre_price'] = $clothingAttrInfo->pre_price;
            $confirm['price'] = $clothingAttrInfo->price;
            $confirm['num'] = $data['num'];
            $confirm['spec'] = $clothingAttrInfo->clothingSpec->name;
            $this->checkSession($confirm, $request);
            $request->session()->push("cart",$confirm);
            session()->save();
            echo json_encode($request->session()->all());
        }else{
            echo 0;
        }
    }
    // 清除session中重复的
    public function checkSession($confirm, $request){
        $data = session("cart");
        if($data){
            foreach ($data as $k => $v) {
                if($v['goods_id'] == $confirm["goods_id"] && $v['spec'] == $confirm['spec']){
                    $request->session()->forget('cart.'.$k);
                }
            }
        }
    }
    // 提交订单
    public function confirm($id,$type){
        // dd(session()->all());
        if($type == 0){
            $data = session("confirm");
            $goodsInfo = array();
            $goodsInfo[0] = $data;
        }else{
            $goodsInfo = session("cart");
        }
        $address = new Address;
        if($id == 0){
            $addressInfo = $address->where("user_id", session("uid"))->where("type", 1)->first();
        }else{
            $addressInfo = $address->find($id);
        }
        if($addressInfo){
            session(["address"=>$addressInfo->id]);
            session()->save();
        }
        return view("home.cart.confirm", ["goodsInfo" => $goodsInfo, "addressInfo" => $addressInfo, "type" => $type]);
    }
    // 支付订单
    public function pay($type, $id, Request $request){
        if($type == 0){
            $data = session("confirm");
        }else if($type == 1){
            $data = session("cart");
        }
        if($type != 2){
            $orders = new Orders;
            $orders->num = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $orders->user_id = session("uid");
            $orders->address_id = session("address");
            $orders->save();
            $ordersInfo = Array();
            $ordersInfo["num"] = $orders->num;
            $ordersInfo["sum"] = 0;
        }
        if($type == 0){
            $data['orders_id'] = $orders->id;
            DB::table("orders_info")->insert($data);
            $ordersInfo["sum"] = $data["price"] * $data["num"];
            $request->session()->forget("confirm");
        }else if($type == 1){
            foreach ($data as $k => $v) {
                $v["orders_id"] = $orders->id;
                DB::table("orders_info")->insert($v);
                $ordersInfo["sum"] = $v["price"] * $v["num"];
            }
            $request->session()->forget("cart");
        }else{
            $orders = new Orders;
            $ordersInfo_temp = $orders->find($id);
            $ordersInfo_temp->num = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $ordersInfo_temp->save();
            $ordersInfo = $orders->find($id)->toArray();
            $ordersInfo["sum"] = 0;
            foreach ($ordersInfo_temp->ordersInfo as $k => $v) {
                $ordersInfo["sum"] += $v->price * $v->num;
            }
        }
        session(["sum" => $ordersInfo["sum"]]);
        session(["num" => $ordersInfo["num"]]);
        session()->save();
        return redirect("/pays");
    }
    //支付
    public function pays(){
        $user = new User;
        $openId = $user->where('id',session('uid'))->first()->open_id;
        $sum = (float)session("sum")*100;
        //发起支付
        $product = [
            'trade_type'       => 'JSAPI',
            // 微信公众号支付填JSAPI
            'body'             => '微信支付',
            'detail'           => '天路本草',
            'out_trade_no'     => session("num"),
            // 这是自己ERP系统里的订单ID，不重复就行。
            'total_fee'        => $sum,
            // 金额，单位只能是分。
            'notify_url'       => 'http://www.tlbc99.com/paySuccess',
            // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $openId,
            // 这个不能少，少了要报错。
        ];
        $order = new Order($product);
        $app = new Application(config('wechat'));
        $payment = $app->payment;
        $result = $payment->prepare($order);
        // 这里的order是上面一步得来的。 这个prepare()帮你计算了校验码，帮你获取了prepareId.省心。
        $prepayId = null;
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            // 这个很重要。有了这个才能调用支付。
        } else {
            var_dump($result);  die("出错了。");
        }
        $config = $payment->configForJSSDKPayment($prepayId);
        // dd($config);
        // 这个方法是取得js里支付所必须的参数用的。没这个啥也做不了，除非你自己把js的参数生成一遍
        $app = new Application(config('wechat'));
        $js = $app->js;  // 这个是jssdk里页面上需要用到的js参数信息。
        // dd($js);
        return view("home.cart.pay", [
            "sum" => session("sum"),
            "num" => session("num"),
            "config" => $config,
            "js"=>$js
        ]);
    }

    // 支付成功回调函数
    public function paySuccess(Request $request){
        $postData = file_get_contents('php://input');
        file_put_contents('./aaa.txt', $postData."\n\n", FILE_APPEND);
        $xml_array = simplexml_load_string($postData, "SimpleXMLElement", LIBXML_NOCDATA);
        $orders = new Orders;
        // dd('xsxsax');
        $ordersInfo = $orders->where("num", $xml_array->out_trade_no)->where("status", 1)->first();
        if(count($ordersInfo)){
            $ordersInfo->transaction_id = $xml_array->transaction_id;
            $ordersInfo->status = 2;
            $ordersInfo->pay_at = date("Y-m-d H:i:s");
            $ordersInfo->save();
        }
    }
    //客服新订单提醒
    // public function orderTemplate(){
    //     $app = app('wechat');
    //     $user = new User;
    //     $orders = new Orders;
    //     $ordersInfo = $orders->where("num", '2017100175971')->first();
    //     $sum=1;
    //     $userInfo = $user->where('id',session('uid'))->first();
    //     $kefuInfo = $user->where('user_type','1')->get();
    //     $notice = $app->notice;
    //     $template_id = 'kg3QU20n8gUugIidJok_9TOVhEKkyZX74udSmMuA76A';
    //     $url = Config::get('app.domain_name').'admin';
    //     $data = array(
    //         "first"=>'您收到了一条新的订单，请及时登录后台处理！',
    //         "keyword1"=>$ordersInfo->num,
    //         "keyword2"=>'天路本草！',
    //         "keyword3"=>$sum,
    //         "keyword4"=>'微信支付',
    //         "keyword5"=>$userInfo->username,
    //         "remark"=>'请及时处理！',
    //     );
    //     // foreach ($kefuInfo as $key => $value) {
    //       $res = $notice->uses($template_id)->withUrl($url)->andData($data)->andReceiver('oPZoxwKddQY6YT_Sekc3ap71zqI0')->send();
    //     // }
    // }

    //申请退款
    public function refund($id){
        // $app = new Application(config('wechat'));
        // $payment = $app->payment;
        // $ordersInfo = new OrdersInfo;
        // $ordersInfoData = $ordersInfo->find($id);
        // $orderNo = $ordersInfoData->orders->transaction_id;
        // $refundNo = $ordersInfoData->orders->num;
        // $res = $payment->refundByTransactionId($orderNo, $refundNo, $ordersInfoData->price);
        // if($res->return_code == "SUCCESS" && $res->result_code == "SUCCESS"){
        //     if($res->return_msg == "OK"){

        //     }
        // }

    }




    // ajax删除购物车商品
    public function delete(Request $request){
        $id = $request->input("id");
        $data = session("cart");
        unset($data[$id]);
        $request->session()->put('cart', $data);
        session()->save();
        echo 1;
    }
    // ajax批量删除购物车商品
    public function deleteAll(Request $request){
        $request->session()->forget('cart');
        session()->save();
        echo 1;
    }
}
